$.omPlugin = {};
$.omPlugin["omButtonbar"] = {
	attrs : [ "width" ]
};
$.omPlugin["omButton"] = {
	attrs : [ "label", "width", "disabled" ],
	methods : [ "changeIcons", "changeLabel", "click", "disable", "enable" ],
	fn : [ "click" ,"onClick" ],
	alias : {
		"click" : "onClick"
	}
};
$.omPlugin["omDialog"] = {
	attrs : [ "autoOpen|b", "closeOnEscape|b", "modal|b", "resizable|b",
			"title", "width", "zIndex", "dialogClass", "draggable|b", "height",
			"maxHeight", "maxWidth", "minWidth", "path", "cacheable|b","buttons|o" ],
	methods : [ "close", "isOpen", "open","option" ],
	fn : [ "onBeforeClose", "onClose", "onOpen" ]
};
$.omPlugin["omDialog-Button"] = {
	attrs : [ "text" ],
	fn : [ "click" ]
};
$.omPlugin["omProgressbar"] = {
	attrs : [ "text", "value|i", "width" ],
	methods : [ "value" ],
	fn : [ "onChange" ]
};
$.omPlugin["omPanel"] = {
	attrs : [ "closable|b", "closed|b", "collapsed|b", "collapsible|b",
			"header|b", "height", "iconCls", "loadingMessage", "preProcess",
			"title", "url", "width" , "label"],
	methods : [ "close", "collapse", "destroy", "expand", "open", "reload",
			"resize", "setIconClass", "setTitle" ],
	fn : [ "onBeforeClose", "onBeforeCollapse", "onBeforeExpand",
			"onBeforeOpen", "onClose", "onCollapse", "onError", "onExpand",
			"onOpen", "onSuccess" ],
	alias : {
		"label" : "title"
	}
};
$.omPlugin["omPanel-Tool"] = {
	attrs : [ "id", "iconCls" ]
};
$.omPlugin["omBorderLayout"] = {
	attrs : [ "fit|b", "hideCollapsBtn|b", "spacing|i" ],
	methods : [ "closeRegion", "collapseRegion", "expandRegion", "openRegion" ]
};
$.omPlugin["omBorderLayout-Panel"] = {
	attrs : function $$push($attr1, $attr2) {
		var $arr = [];
		function $push($a) {
			$.each($a, function(i, v) {
				$arr.push(v);
			});
		}
		;
		$push($attr1);
		$push($attr2);
		return $arr;
	}($.omPlugin["omPanel"].attrs, [ "region", "expandToBottom|b",
			"expandToTop|b" ]),
	alias : {
		"label" : "title"
	}
};
$.omPlugin["omTabs"] = {
	attrs : [ "active", "autoPlay|b", "border|b", "closable|b", "height",
			"interval", "lazyLoad|b", "scrollable|b", "switchMode",
			"tabHeight", "tabMenu|b", "tabWidth", "width" ],
	methods : [ "activate", "add", "close", "closeAll", "doLayout",
			"getActivated", "getAlter", "getLength", "reload", "setDataSource" ],
	fn : [ "onActivate", "onAdd", "onBeforeActivate", "onBeforeAdd",
			"onBeforeClose", "onBeforeCloseAll", "onClose", "onCloseAll",
			"onLoadComplete" ]
};
$.omPlugin["omAccordion"] = {
	attrs : [ "active", "autoPlay|b", "collapsible|b", "disabled|b", "header",
			"height", "iconCls", "interval|i", "switchEffect|b", "switchMode",
			"width" ],
	methods : [ "activate", "disable", "enable", "getActivated", "getLength",
			"reload", "setTitle", "url" ],
	fn : [ "onActivate", "onBeforeActivate", "onBeforeCollapse", "onCollapse" ]
};
$.omPlugin["omMenu"] = {
	attrs : [ "contextMenu|b", "dataSource", "maxWidth|i", "minWidth|i",
			"container", "popup" ],
	methods : [ "disableItem", "enableItem", "hide", "show" ],
	fn : [ "onSelect" ]
};
$.omPlugin["omMenu-Model"] = {
	attrs : [ "id", "label", "url", "seperator|b", "icon" ]
};
$.omPlugin["omTooltip"] = {
	attrs : [ "anchor|b", "anchorOffset", "contentEL", "delay|i", "height",
			"html", "lazyLoad", "maxHeight", "maxWidth", "minHeight",
			"minWidth", "offset", "region", "showOn", "trackMouse", "url",
			"width", "rendererTo" ],
	methods : [ "hide", "show" ]
};

$.omPlugin["omGrid"] = {
	attrs : [ "width", "height", "title", "autoFit|b", "dataSource",
			"editMode", "emptyMsg", "errorMsg", "extraData", "limit",
			"loadingMsg", "method", "pageStat", "pageText", "rowClasses",
			"showIndex|b", "singleSelect|b","colModel|a" ],
	methods : [ "cancelChanges", "cancelEdit", "deleteRow", "editRow",
			"getChanges", "getData", "getSelections", "insertRow", "refresh",
			"reload", "resize", "saveChanges", "setData", "setSelections" ,"option"],
	fn : [ "onAfterEdit", "onBeforeEdit", "onCancelEdit", "onError",
			"onPageChange", "onRefresh", "onRowClick", "onRowDblClick",
			"onRowDeselect", "onRowSelect", "onSuccess" ]
};
$.omPlugin["omGrid-ColModel"] = {
	attrs : [ "header", "name", "width", "align" ],
	fn:["renderer"]
};
$.omPlugin["omTree"] = {
	attrs : [ "cascadeCheck|b", "dataSource", "draggable|b", "showCheckbox|b",
			"showIcon|b", "simpleDataModel|b" ],
	methods : [ "check", "checkAll", "collapse", "collapseAll", "expand",
			"expandAll", "findByNId", "findNode", "findNodeBy", "findNodes",
			"findNodesBy", "getChecked", "getChildren", "getData", "getParent",
			"getSelected", "insert", "isCheck", "modify", "refresh", "remove",
			"select", "setData", "uncheck", "unselect" ],
	fn : [ "onBeforeCollapse", "onBeforeExpand", "onBeforeLoad",
			"onBeforeSelect", "onCheck", "onClick", "onCollapse", "onDblClick",
			"onDrag", "onDrop", "onError", "onExpand", "onRightClick",
			"onSelect", "onSuccess" ],
	fnAlias : {
		"click" : "onClick"
	}
};
$.omPlugin["omTree-Model"] = {
	attrs : [ "id", "text", "expanded|b", "classes", "icon" ]
};
/**
 * 对页面中的控件以定义的class进行初始化
 * 
 * @param $config
 *            预定义的配置信息
 */
function initUI($config) {
	var $$config = $config || {};
	// 清理浏览器内存,只对IE起效
	$(document).ajaxStart(function() {
		//
	}).ajaxStop(function() {
		//
	});

	function $generateId($uiType) {
		$uiType = $uiType || "Control";
		var idCounter = $(window).data("_ID_COUNTER") || 10000;
		var $ret = $uiType + "_" + idCounter;
		$(window).data("_ID_COUNTER", ++idCounter);
		return $ret;
	}
	/**
	 * 从扩展标签中提取属性的定义
	 */
	function $buildConfig($obj, $uiType) {
		// 这里的id一定需要
		var $config = {
			id : $obj.attr("id"),
			attr : function(name) {
				return $obj.attr(name);
			}
		};
		var ele = $config.element = $obj;
		if (!$config.id) {
			$config.id = $generateId($uiType);
			$obj.attr("id", $config.id);
		} else {
			// 从initUI的参数中查找有没有相应的配置信息
			if ($.isPlainObject($$config[$config.id])) {
				$.each($$config[$config.id], function(k, v) {
					$config[k] = v;
				});
			}
		}
		var $arrAttr = null;
		var $arrFn = null;
		// 从扩展属性fn中取出事件的配置
		if ($obj.attr("fn")) {
			var fn = $convertData($obj.attr("fn"), "o", $uiType, "fn");
			$.extend($config, fn);
		}
		// 加载扩展属性和事件
		if ($uiType && $.omPlugin[$uiType]) {
			$arrAttr = $.omPlugin[$uiType].attrs;
			$arrFn = $.omPlugin[$uiType].fn;
		}
		$.isArray($arrAttr)&& $.each($arrAttr, function(i, attr) {
			var $attrN = attr;// 属性名称
			var $attrT = null;// 属性类型
			if (attr && attr.length > 2
					&& attr.charAt(attr.length - 2) == "|") {// 最后一位表示的是数据类型
				$attrN = attr.substring(0, attr.length - 2);
				$attrT = attr.charAt(attr.length - 1);
			}
			var $v = $obj.attr($attrN);
			if ($v) {
				$v = $convertData($v, $attrT, $uiType, $attrN);
			}
			if (typeof ($v) != "undefined") {
				($config[$attrN] = $v);
			}
		});
		$.isArray($arrFn) && $.each($arrFn,function(i, fn) {
			var $fnStr = $obj.attr(fn);
			if ($fnStr) {
				$config[fn] = $convertData($fnStr, "f",
						$uiType, fn);
			}
		});
		if($.omPlugin[$uiType].alias){
			$.each($.omPlugin[$uiType].alias,function(key,alias){
				if(typeof($config[key])!="undefined"){
					$config[alias]=$config[key];
				}
			});
		}
		return $config;
	}
	/**
	 * 将字符串表示的数据转换为对应数据类型的数据,如果不能使用指定的数据类型进行转换时，将会把原数据返回
	 */
	function $convertData(value, type, uiType, attrName) {
		if (typeof (value) != "string") {
			return value;
		}
		if (typeof (type) == "undefined" || type === "s" || type == null
				|| type == "") {
			return value;
		}
		if (type === "b") {// boolean型
			return value === "true" ? true : value === "false" ? false : value;
		}
		if (type === "i") {// int型
			var v = parseFloat(value);
			return isNaN(v) ? value : v;
		}
		if (type === "f") {// function
			eval("var $fn=" + value);
			return $fn;
		}
		if (type === "a") {// array
			return eval(value);
		}
		if (type === "o") {// json对象
			return eval("(" + value + ")");
		}
	}
	/**
	 * 创建UI对象，并将对象ID作为句柄附加给window对象，以快速调用其方法
	 */
	function $buildUI($obj, $uiType, $config) {

		var $ui = $obj[$uiType]($config);
		var $dom = $obj[0];
		$dom._ui = $dom.$ = $ui;
		var $instance = $ui.data($uiType);
		var $arrMethod = null;
		if ($uiType && $.omPlugin[$uiType]) {
			$arrMethod = $.omPlugin[$uiType].methods;
		}
		$.isArray($arrMethod) && $.each($arrMethod, function(i, method) {
			if ($instance && $.isFunction($instance[method])) {
				$dom[method] = function() {
					// 暴露公共函数
					return $instance[method].apply($instance, arguments);
				};
			}
		});
		return $ui;
	}
	/**
	 * 对指定类型的OM-UI组件进行初始化操作，通过类选择器选择进行页面元素的选择
	 * 
	 * @param uiType
	 *            需要进行初始化的OM-UI组件类型,如omTabs,omAccordion
	 * @param cls
	 *            元素的类选择器
	 */
	function $$initUIType(uiType, cls) {
		if ($.fn[uiType] && cls) {
			$(cls).each(function() {
				var $this = $(this);
				var $config = $buildConfig($this, uiType);
				$buildUI($this, uiType, $config);
			});
		}
	}

	// buttonbar工具栏及button
	if ($.fn.omButtonbar && $.fn.omButton) {
		/**
		 * 生成按钮的配置信息
		 */
		function $buildButtonConfig($obj) {
			var $config = $buildConfig($obj, "omButton");
			return $.extend($config, {
				label : $config.label || $obj.attr("label") || null,
				icons : {
					left : $obj.attr("left-icon") || null,
					right : $obj.attr("right-icon") || null
				}
			});
		}
		$(".ui-buttonbar").each(function() {
			var $this = $(this);
			var $config = $buildConfig($this, "omButtonbar");
			var $buttons = [];
			$(".ui-button", $this).each(function() {
				$buttons.push($buildButtonConfig($(this)));
				$(this).remove();
			});
			$config.btns = $buttons;
			$buildUI($this, "omButtonbar", $config);
		});

		$(".ui-button").each(function() {
			var $this = $(this);
			if (!$this.parent(".ui-buttonbar").length) {
				$buildUI($this, "omButton", $buildButtonConfig($this));
			}
		});
	}
	// menu
	if ($.fn.omMenu) {
		/**
		 * 从本地标签定义中加载dataSource
		 * 
		 * @param $obj
		 * @param $parent
		 * @returns {Array}
		 */
		function $buildMenuModel($obj, $parent) {
			var items = [];
			$(">span", $obj).each(function(i, obj) {
				var $this = $(this);
				var $itemConfig = $buildConfig($this, "omMenu-Model");
				$buildMenuModel($this, $itemConfig);
				items.push($itemConfig);
			});
			if ($parent && items.length > 0) {
				$parent.children = items;
			}
			return items;
		}
		$(".ui-menu").each(function() {
			var $this = $(this);
			var $config = $buildConfig($this, "omMenu");

			var $menuModelDiv = $("div.ui-menu-model", $this);
			if (!$config.dataSource && $menuModelDiv.length) {
				// 通过div标签来实现的dataSource
				$config.dataSource = $buildMenuModel($menuModelDiv);
			}
			if(!$config.container && $config.popup && !$config.contextMenu){
				$config.contextMenu=true;
			}
			var $ui = $buildUI($this, "omMenu", $config);
			var $ins = $ui.data("omMenu");
			if ($config.container) {// 用于展示该菜单的容器
				$.each($config.container.split(","), function(i, c) {
					$(c).mouseover(function(e) {
						$ins.show(this);
					});
				});
			} else if ($config.popup) {// 用于绑定右键菜单的容器,不能于$config.container同时使用
				$.each($config.popup.split(","), function(i, c) {
					$(c).bind("contextmenu", function(event) {
						$ins.show(event);
					});
				});
			}
		});
	}
	// dialog
	if ($.fn.omDialog) {
		$(".ui-dialog").each(function() {
			var $this = $(this);
			var $config = $buildConfig($this, "omDialog");
			$config._onOpen = $config.onOpen;
			$config.onOpen = function(event) {
				if ($config._onOpen) {
					$config._onOpen(event);
				}
				var $ui = $config.element;
				var $ins = $ui.data("omDialog");
				var path=$ins.option("path");
				if(path){//打开的是一个外部的链接页面
					var $frame=$(".ui-dialog-frame",$ui);
					if(!$frame.length){//初次打开
						if (typeof ($config.cacheable) == "undefined") {
							$config.cacheable = true;
						}
						$frame = $('<iframe class="ui-dialog-frame" frameborder="0" height="100%" width="100%"></iframe>')
						$this.append($frame);
						$config._init=true;
					}
					if (!$frame.attr("src") || !$config.cacheable || $config.cacheable && $config.path!=$frame.attr("src")) {
						//需要重新加载页面
						$frame.attr("src", path);
					}
				}
			}
			if(!$config.buttons || !$config.buttons.length || $config.buttons.length==0){
				var $buttons = [];
				$(".ui-dialog-button", $this).each(function(){
					var $btnConfig = $buildConfig($(this),"omDialog-Button");
					$buttons.push($btnConfig);
				});
				$config.buttons = $buttons;
			}
			var $ui=$buildUI($this, "omDialog", $config);
		});
	}
	// panel
	if ($.fn.omPanel) {
		$(".ui-panel").each(function() {
			var $this = $(this);
			var $config = $buildConfig($this, "omPanel");
			var $tools = [];
			$(".ui-panel-tool", $this).each(function() {
				var $tool = $buildConfig($(this), "omPanel-Tool");
				$tools.push($tool);
			});
			$config.tools = $tools;
			$buildUI($this, "omPanel", $config);
		});
	}
	// borderLayout
	if ($.fn.omBorderLayout) {
		$(".ui-border-layout").each(function() {
			var $this = $(this);
			var $config = $buildConfig($this, "omBorderLayout");
			var $panels = [];
			$(".ui-border-layout-panel", $this).each(function() {
				var $panel = $buildConfig($(this), "omBorderLayout-Panel");
				$panels.push($panel);
			});
			$config.panels = $panels;
			$buildUI($this, "omBorderLayout", $config);
		});
	}
	// tooltip
	if ($.fn.omTooltip) {
		$(".ui-tooltip").each(function() {
			var $this = $(this);
			var $config = $buildConfig($this, "omTooltip");
			if (!$config.contentEL && !$config.html && !$config.url) {
				$config.html = $this.html();
			}
			var $container = [];
			if ($config.rendererTo) {
				$.each($config.rendererTo.split(","), function(i, v) {
					if (v) {
						$container.push($(v))
					}
					;
				});
			} else {
				$container.push($this.parent());
			}
			$.each($container, function(i, v) {
				$buildUI(v, "omTooltip", $config);
			});
			$this.remove();
		});
	}
	// grid
	if ($.fn.omGrid) {
		var $$deep = 0;// 标题的总深度
		var $$colModel = [];
		var $adjustSpan = function($obj, $ss, $oldAdjust) {
			if (!$obj.is(".ui-grid-colmodel")) {
				var $pOldAdjust = $obj.data("$ss");
				var $pSS = $pOldAdjust + $ss - $oldAdjust;
				$obj.data("$ss", $pSS);
				$adjustSpan($obj.parent(), $pSS, $pOldAdjust);
			}
		}
		var $analysisColModel = function($obj, deep) {
			if (deep > 0) {
				$obj.data("$dd", deep);// 当前标题的深度调整值
				$obj.data("$ss", 1);// 当前标题的横跨度
				if (deep > $$deep) {
					$$deep = deep;
				}
				if (deep > $$colModel.length) {
					$$colModel.push([]);
				}
				$$colModel[deep - 1].push($obj);
			}
			var children = $(">span", $obj);
			if (children.length) {
				$adjustSpan($obj, children.length, 1);
				$obj.data("$hasChildren", 1);
				children.each(function() {
					$analysisColModel($(this), deep + 1);
				});
			}
		}
		$.omWidget.addInitListener('om.omGrid', function() {
			//为grid增加panel
			var self = this, op=this.options,grid = this.element.closest('.om-grid');
			if(op._gridPanel){
				$(op._gridPanel).addClass("panelDiv");
				// 将gridPanel放在titleDiv之后
				self.titleDiv.after(op._gridPanel);
				self.panelDiv = op._gridPanel;
			}
			self._base_resetHeight=self._resetHeight;
			self._resetHeight=function(){
				self._base_resetHeight();
				if(!self.panelDiv){
					return;
				}
				var gridBody = grid.children('.bDiv');
				var panelHeight = self.panelDiv.outerHeight(true);
				gridBody.outerHeight(gridBody.outerHeight(true) - panelHeight);
			}
			self._resetHeight();//初始化完成之后，需要先调用一次计算
		});
		$(".ui-grid").each(function() {
			var $this = $(this);
			var $gridPanel = $(".ui-grid-panel", $this);// 附加给表格的额外面板,用于进行数据检索，工具条等
			var $gridConfig = $buildConfig($this, "omGrid");
			if ($gridPanel.length) {
				$gridConfig._gridPanel = $gridPanel;
			}
			var $grid = $("<table></table>");// 实际被用于展示grid的table
			$grid.attr("id", $gridConfig.id);
			$this.after($grid);
			var $divColModel = $(".ui-grid-colmodel", $this);
			if(!$gridConfig.colModel && $divColModel.length){
				$$deep = 0;
				$$colModel = [];
				var $colModel = [];
				$analysisColModel($divColModel, 0);
				if ($$deep == 1) {
					$.each($$colModel[0], function(i, v) {
						var $config = $buildConfig(v, "omGrid-ColModel");
						$colModel.push($config);
					});
				} else {
					$.each($$colModel, function(row, rowModel) {
						var $rowModel = [];
						$.each(rowModel, function(i, v) {
							var $config = $buildConfig(v, "omGrid-ColModel");
							$config.colspan = v.data("$ss");
							if (!v.data("$hasChildren")) {
								$config.rowspan = $$deep - v.data("$dd") + 1;
							}
							$rowModel.push($config);
						});
						$colModel.push($rowModel);
					});
				}
				$gridConfig.colModel = $colModel;
			}
			$buildUI($grid, "omGrid", $gridConfig);
			$this.remove();// 将原来用来进行表格定义的div给移除掉
		});
	}

	// tree
	if ($.fn.omTree) {
		/**
		 * 从本地标签定义中加载dataSource
		 * 
		 * @param $obj
		 * @param $parent
		 * @returns {Array}
		 */
		function $buildTreeModel($obj, $parent) {
			var nodes = [];
			$(">span", $obj).each(function(i, obj) {
				var $this = $(this);
				var $nodeConfig = $buildConfig($this, "omTree-Model");
				if (!$nodeConfig.classes && $nodeConfig.icon) {
					$nodeConfig.classes = $getTreeNodeClass($nodeConfig.icon);
				}
				$buildTreeModel($this, $nodeConfig);
				nodes.push($nodeConfig);
			});
			if ($parent && nodes.length > 1) {
				$parent.children = nodes;
			}
			return nodes;
		}
		// 为树结点生成图标
		var $css = {};// 以icon路径作为key,对应的class作为value进行存储
		function $getTreeNodeClass($icon) {
			if (!$css[$icon]) {
				$css[$icon] = $generateId("ui-tree-node-icon");
			}
			return $css[$icon];
		}
		function $writeCSS() {
			var content = "<style type='text/css'>";
			$.each($css, function(icon, cls) {
				content += "\nli.om-tree-node span." + cls
						+ ", li.om-tree-node.expandable span." + cls
						+ "{background:url(\"" + icon + "\") no-repeat;}";
			});
			content += "</style>";
			$("head").append(content);
		}
		$(".ui-tree").each(function() {
			var $this = $(this);
			var $config = $buildConfig($this, "omTree");
			var $treeModelDiv = $("div.ui-tree-model", $this);
			if (!$config.dataSource && $treeModelDiv.length) {
				// 通过div标签来实现的dataSource
				$config.dataSource = $buildTreeModel($treeModelDiv);
				$config.simpleDataModel = false;
			}
			var $ui = $buildUI($this, "omTree", $config);
		});
		$writeCSS();
	}

	// 一些简单的组件，可以直接通过$$initUIType进行初始化。
	$$initUIType("omProgressbar", ".ui-progressbar");
	$$initUIType("omTabs", ".ui-tabs");
	$$initUIType("omAccordion", ".ui-accordion");
}